﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Dynamic;

namespace Util
{
    public class Ocr
    {
        static string APP_ID = "26666033";
        static string API_KEY = "7Z6sLHcFX7D0xTAFAGj9NlRm";
        static string SECRET_KEY = "8uyCX7ExM3X5agmzBBPIu9eeVTiXf3wO";
        public static dynamic GetIdCard(string Path)
        {
            // 设置APPID/AK/SK

            var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
            client.Timeout = 60000;  // 修改超时时间

            var image = File.ReadAllBytes(Path);
            var idCardSide = "front";

            // 调用身份证识别，可能会抛出网络等异常，请使用try/catch捕获
            var result = client.Idcard(image, idCardSide);
            Console.WriteLine(result);
            // 如果有可选参数
            var options = new Dictionary<string, object>{
                {"detect_direction", "true"},
                {"detect_risk", "false"}
            };
            // 带参数调用身份证识别
            var obj = client.Idcard(image, idCardSide, options);
            string o = JsonConvert.SerializeObject(obj);
            dynamic json = new WeiXin().ConvertJson(o);
            dynamic m = new ExpandoObject();
            m.RealName = json.words_result.姓名.words;
            m.Sex = json.words_result.性别.words;
            m.Address = json.words_result.住址.words;
            m.IdCard = json.words_result.公民身份号码.words;
            m.Age = GetAge(json.words_result.出生.words);
            return m;
        }
        public static int GetAge(string Birthday)
        {
            string Year = Birthday.Substring(0, 4);
            string Month = Birthday.Substring(4,2);
            string Day = Birthday.Substring(6, 2);
            return Common.DateDiff(DataConvert.ToDateTime(Year + "-" + Month + "-" + Day), DateTime.Now, "Y");
        }
    }
}
